package com.beiing.tianshuai.tianshuai.dongtai.ui;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.adapter.DynamicAllMessageAdapter;
import com.beiing.tianshuai.tianshuai.base.BaseFragment;
import com.beiing.tianshuai.tianshuai.dongtai.DynamicRelayDetailActivity;
import com.beiing.tianshuai.tianshuai.dongtai.view.DynamicDetailActivity;
import com.beiing.tianshuai.tianshuai.entity.DynamicAllMessageBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.mine.ui.NewPersonalIndexActivity;
import com.beiing.tianshuai.tianshuai.network.DataManager;
import com.beiing.tianshuai.tianshuai.util.DensityUtils;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.CustomEmptyLayout;
import com.beiing.tianshuai.tianshuai.widget.MyRefreshHeader;
import com.beiing.tianshuai.tianshuai.widget.RecycleViewDivider;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

/**
 * A simple {@link Fragment} subclass.
 */
public class DynamicAllMessageFragment extends BaseFragment {

    @BindView(R.id.empty_view)
    CustomEmptyLayout mEmptyLayout;
    @BindView(R.id.refresh_header)
    MyRefreshHeader mRefreshHeader;
    @BindView(R.id.rcv_dynamic_all_message)
    RecyclerView mRcvDynamicAllMessage;
    @BindView(R.id.refresh_footer)
    ClassicsFooter mRefreshFooter;
    @BindView(R.id.smart_refreshLayout)
    SmartRefreshLayout mSmartRefreshLayout;

    /**
     * 当前登录的用户id
     */
    private String mUid;

    /**
     * 请求更多数据的起始位置
     */
    private int mFirstRow = 0;

    /**
     * 请求更多数据的条目数量
     */
    private int mListRows = 20;

    /**
     * 是否加载所有数据
     */
    private boolean isLoadFinish;

    /**
     * recycler view 适配器
     */
    private DynamicAllMessageAdapter mAdapter;

    /**
     * 网络重连次数
     */
    private int retryCount = 1;

    private DisposableObserver<DynamicAllMessageBean> mObserver;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_dynamic_all_message;
    }

    @Override
    protected void init(View contentView) {
        mUid = UserInfoBean.getUid(mContext);
        initRecyclerView();
        initRefreshLayout();
        initListener();
        loadData(mUid, mFirstRow, mListRows);
    }

    private void initRecyclerView() {
        // 设置adapter
        mAdapter = new DynamicAllMessageAdapter(mContext);
        mRcvDynamicAllMessage.setAdapter(mAdapter);

        // 设置layoutManager
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        mRcvDynamicAllMessage.setLayoutManager(layoutManager);
        // 绘制item间的分割线，
        mRcvDynamicAllMessage.addItemDecoration(
                new RecycleViewDivider(
                        mContext, LinearLayoutManager.HORIZONTAL, DensityUtils.dp2px(mContext, 0.5f),
                        ContextCompat.getColor(mContext, R.color.common_gray_background))
        );
    }

    private void initListener() {
        // recyclerView点击事件
        mAdapter.setListener(new DynamicAllMessageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(DynamicAllMessageBean.DataBean.NumberBean bean, int position) {
                boolean isReply = !TextUtils.isEmpty(bean.getCommentContent());
                Intent intent = new Intent();
                switch (bean.getTableType()) {
                    case "0":
                        // 评论和点赞 type = 0 进入普通详情
                        intent.setClass(mContext, DynamicDetailActivity.class);
                        break;
                    case "1":
                        // 评论和点赞 type = 1 点赞进入普通详情 评论进入转发详情
                        intent.setClass(mContext, isReply ? DynamicRelayDetailActivity.class : DynamicDetailActivity.class);
                        break;
                    case "2":
                        // 评论和点赞 type = 2 点赞进入转发详情 评论进入普通详情
                        intent.setClass(mContext, !isReply ? DynamicRelayDetailActivity.class : DynamicDetailActivity.class);
                        break;
                    case "3":
                        // 评论和点赞 type = 3 进入转发详情
                        intent.setClass(mContext, DynamicRelayDetailActivity.class);
                        break;
                    default:
                        break;
                }
                intent.putExtra("dynamic_id", bean.getToId());
                startActivity(intent);
            }

            @Override
            public void onAvatarClick(DynamicAllMessageBean.DataBean.NumberBean bean, int position) {
                Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                intent.putExtra("uid", bean.getUid());
                startActivity(intent);
            }
        });

        // 下拉上拉监听
        mSmartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                if (!isLoadFinish) {
                    loadData(mUid, mFirstRow, mListRows);
                }
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if (getActivity() != null) {
                    ((DynamicMessageActivity) getActivity()).consumeReplyMarks(UserInfoBean.getUid(mContext));
                    ((DynamicMessageActivity) getActivity()).consumePraiseMarks(UserInfoBean.getUid(mContext));
                }
                isLoadFinish = false;
                mFirstRow = 0;
                loadData(mUid, mFirstRow, mListRows);
            }
        });
    }

    private void initRefreshLayout() {
        mSmartRefreshLayout.setRefreshHeader(new MyRefreshHeader(mContext));
        mSmartRefreshLayout.setRefreshFooter(new ClassicsFooter(mContext));
    }

    private void loadData(String uid, final int firstRow, final int listRows) {
        showProgress();
        mObserver = new DisposableObserver<DynamicAllMessageBean>() {
            @Override
            public void onNext(DynamicAllMessageBean dynamicAllMessageBean) {
                if (dynamicAllMessageBean.getCode() == 200) {
                    List<DynamicAllMessageBean.DataBean.NumberBean> beanList = dynamicAllMessageBean.getData().getNumber();
                    int size = beanList.size();
                    if (mSmartRefreshLayout != null && (mSmartRefreshLayout.isRefreshing() || mSmartRefreshLayout.isLoading())) {
                        mSmartRefreshLayout.finishRefresh();
                        mSmartRefreshLayout.finishLoadmore();
                    }
                    if (size == 0) {
                        if (mAdapter.getList().isEmpty()) {
                            mEmptyLayout.setEmptyView(R.drawable.bg_empty_warning, "空空的");
                        }
                        isLoadFinish = true;
                        mSmartRefreshLayout.setLoadmoreFinished(true);
                    } else if (size < mListRows * 2) {
                        isLoadFinish = false;
                        mFirstRow += size;
                        if (mSmartRefreshLayout != null) {
                            if (mSmartRefreshLayout.isRefreshing()) {
                                mAdapter.updateData(beanList);
                            } else {
                                mAdapter.appendData(beanList);
                            }
                        }
                        if (mSmartRefreshLayout != null) {
                            mSmartRefreshLayout.setLoadmoreFinished(false);
                        }
                    } else if (size == mListRows * 2) {
                        isLoadFinish = false;
                        mFirstRow += size;
                        if (mSmartRefreshLayout != null) {
                            if (mSmartRefreshLayout.isRefreshing()) {
                                mAdapter.updateData(beanList);
                            } else {
                                mAdapter.appendData(beanList);
                            }
                        }
                        if (mSmartRefreshLayout != null) {
                            mSmartRefreshLayout.setLoadmoreFinished(false);
                        }
                    }
                }
                hideProgress();
            }

            @Override
            public void onError(Throwable e) {
                if (retryCount < 5) {
                    retryCount++;
                    loadData(mUid, firstRow, listRows);
                } else {
                    retryCount = 0;
                    hideProgress();
                    showShortText("请求失败");
                    if (mSmartRefreshLayout.isRefreshing()) {
                        mSmartRefreshLayout.finishRefresh(false);
                    }
                    if (mSmartRefreshLayout.isLoading()) {
                        mSmartRefreshLayout.finishLoadmore(false);
                    }
                    LogUtils.e("获取全部动态消息失败 " + e.getMessage(), "DynamicAllMsg");
                }
            }

            @Override
            public void onComplete() {
                LogUtils.i("获取全部动态消息结束", "DynamicAllMsg");
            }
        };

        Observable<DynamicAllMessageBean> observable = DataManager.getDynamicAllMessage(uid, firstRow, listRows);
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(mObserver);
    }

    private void showProgress() {
        if (mSmartRefreshLayout != null && !mSmartRefreshLayout.isRefreshing() && !mSmartRefreshLayout.isLoading()) {
            mEmptyLayout.setInProgress();
        }
    }

    private void hideProgress() {
        if (mEmptyLayout != null) {
            mEmptyLayout.setChildrenVisible();
        }
    }

    @Override
    public void onDestroy() {
        if (mObserver != null) {
            mObserver.dispose();
        }
        super.onDestroy();
    }
}
